package com.chuan.syn;

//不安全买票
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station,"小明").start();
        new Thread(station,"小红").start();
        new Thread(station,"黄牛").start();
    }
}


class BuyTicket implements Runnable{
    //票
    private int ticketNums = 10;
    //外部停止
    boolean flag = true;

    @Override
    public void run() {
        //买票
        while(flag){
            try {
                Thread.sleep(100);
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    private synchronized void buy() throws InterruptedException {
        if(ticketNums<=0){
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName()+"获取"+ticketNums--);
    }
}